<script setup>
import { defineOptions } from 'vue'
import { ref, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { logout } from '@/api/user'
import { message } from 'ant-design-vue'

defineOptions({
  name: 'AppLayout',
})

const router = useRouter()
const route = useRoute()

const collapsed = ref(false)

// 当前用户角色（从 sessionStorage 获取）
const currentRole = computed(() => {
  if (typeof window === 'undefined' || !window.sessionStorage) {
    return ''
  }
  return sessionStorage.getItem('userRole') || ''
})

// 根据角色定义可见菜单
const roleMenus = {
  人事专员: {
    archive: [
      { key: '/archive/register', label: '档案登记', icon: '📝' },
      { key: '/archive/query', label: '档案查询', icon: '🔍' },
      { key: '/archive/delete', label: '档案删除', icon: '🗑️' },
    ],
  },
  复核专员: {
    archive: [{ key: '/archive/review', label: '档案复核', icon: '✅' }],
    salary: [
      { key: '/salary/standard-review', label: '薪酬标准复核', icon: '✅' },
      { key: '/salary/standard-query', label: '薪酬标准查询', icon: '🔍' },
      { key: '/salary/pay-review', label: '薪酬发放复核', icon: '✅' },
      { key: '/salary/pay-query', label: '薪酬发放查询', icon: '📊' },
    ],
  },
  部门经理: {
    archive: [{ key: '/archive/query', label: '档案查询', icon: '🔍' }],
    salary: [
      { key: '/salary/standard-query', label: '薪酬标准查询', icon: '🔍' },
      { key: '/salary/pay-query', label: '薪酬发放查询', icon: '📊' },
    ],
  },
  普通员工: {
    archive: [{ key: '/archive/query', label: '档案查询', icon: '🔍' }],
    salary: [{ key: '/salary/pay-query', label: '薪酬发放查询', icon: '📊' }],
  },
  系统专员: {
    system: [
      { key: '/system/organization', label: '机构关系设置', icon: '🏢' },
      { key: '/system/position', label: '职位设置', icon: '👔' },
    ],
  },
  薪酬专员: {
    salary: [
      { key: '/salary/standard-register', label: '薪酬标准登记', icon: '📋' },
      { key: '/salary/standard-query', label: '薪酬标准查询', icon: '🔍' },
      { key: '/salary/standard-change', label: '薪酬标准变更', icon: '✏️' },
      { key: '/salary/pay-register', label: '薪酬发放登记', icon: '💰' },
      { key: '/salary/pay-query', label: '薪酬发放查询', icon: '📊' },
    ],
  },
  权限管理员: {
    role: [{ key: '/role', label: '角色管理', icon: '👥' }],
  },
}

const menuItems = computed(() => {
  // 如果没有角色，返回空菜单
  if (!currentRole.value) {
    return {
      system: [],
      archive: [],
      salary: [],
      role: [],
    }
  }
  const menus = roleMenus[currentRole.value] || {}
  return {
    system: menus.system || [],
    archive: menus.archive || [],
    salary: menus.salary || [],
    role: menus.role || [],
  }
})

const selectedKeys = ref([route.path])

// 监听路由变化，更新选中状态
watch(
  () => route.path,
  (newPath) => {
    selectedKeys.value = [newPath]
  },
  { immediate: true },
)

const handleMenuClick = (key) => {
  router.push(key)
  selectedKeys.value = [key]
}

// 处理登出
const handleLogout = async () => {
  try {
    await logout()
    // 清除本地存储
    sessionStorage.removeItem('token')
    sessionStorage.removeItem('userRole')
    sessionStorage.removeItem('userId')
    sessionStorage.removeItem('userName')
    sessionStorage.removeItem('userEmail')

    message.success('登出成功')
    // 跳转到登录页
    router.push('/')
  } catch {
    // 即使登出接口失败，也清除本地存储并跳转
    sessionStorage.removeItem('token')
    sessionStorage.removeItem('userRole')
    sessionStorage.removeItem('userId')
    sessionStorage.removeItem('userName')
    sessionStorage.removeItem('userEmail')
    router.push('/')
  }
}
</script>

<template>
  <div class="layout-container">
    <aside class="sidebar" :class="{ collapsed }">
      <div class="sidebar-header">
        <div class="logo">
          <svg
            width="32"
            height="32"
            viewBox="0 0 40 40"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
          >
            <rect width="40" height="40" rx="12" fill="white" fill-opacity="0.9" />
            <path d="M20 10L20 30" stroke="#007AFF" stroke-width="3" stroke-linecap="round" />
            <path d="M10 20L30 20" stroke="#007AFF" stroke-width="3" stroke-linecap="round" />
          </svg>
          <span v-if="!collapsed" class="logo-text">HR Portal</span>
        </div>
        <button class="collapse-btn" @click="collapsed = !collapsed">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path v-if="!collapsed" d="M9 18l6-6-6-6" />
            <path v-else d="M15 18l-6-6 6-6" />
          </svg>
        </button>
      </div>

      <div class="user-info" v-if="!collapsed">
        <div
          class="user-role"
          :title="
            currentRole ||
            '未设置角色，请在浏览器控制台执行: sessionStorage.setItem(\'userRole\', \'权限管理员\')'
          "
        >
          {{ currentRole || '未设置角色' }}
        </div>
        <button class="logout-btn" @click="handleLogout">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path>
            <polyline points="16 17 21 12 16 7"></polyline>
            <line x1="21" y1="12" x2="9" y2="12"></line>
          </svg>
          <span>登出</span>
        </button>
      </div>
      <div v-else class="user-info-collapsed">
        <button class="logout-btn-collapsed" @click="handleLogout" title="登出">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path>
            <polyline points="16 17 21 12 16 7"></polyline>
            <line x1="21" y1="12" x2="9" y2="12"></line>
          </svg>
        </button>
      </div>

      <nav class="menu">
        <div v-if="menuItems.system.length > 0" class="menu-section">
          <div class="menu-title" :class="{ collapsed }">
            <span class="menu-icon">⚙️</span>
            <span v-if="!collapsed" class="menu-label">系统设置</span>
          </div>
          <div v-if="!collapsed" class="menu-children">
            <a
              v-for="item in menuItems.system"
              :key="item.key"
              :class="['menu-item', { active: selectedKeys.includes(item.key) }]"
              @click="handleMenuClick(item.key)"
            >
              <span class="menu-item-icon">{{ item.icon }}</span>
              <span class="menu-item-label">{{ item.label }}</span>
            </a>
          </div>
          <div v-else class="menu-children-collapsed">
            <a
              v-for="item in menuItems.system"
              :key="item.key"
              :class="['menu-item-collapsed', { active: selectedKeys.includes(item.key) }]"
              @click="handleMenuClick(item.key)"
              :title="item.label"
            >
              {{ item.icon }}
            </a>
          </div>
        </div>
        <div v-if="menuItems.archive.length > 0" class="menu-section">
          <div class="menu-title" :class="{ collapsed }">
            <span class="menu-icon">📁</span>
            <span v-if="!collapsed" class="menu-label">档案管理</span>
          </div>
          <div v-if="!collapsed" class="menu-children">
            <a
              v-for="item in menuItems.archive"
              :key="item.key"
              :class="['menu-item', { active: selectedKeys.includes(item.key) }]"
              @click="handleMenuClick(item.key)"
            >
              <span class="menu-item-icon">{{ item.icon }}</span>
              <span class="menu-item-label">{{ item.label }}</span>
            </a>
          </div>
          <div v-else class="menu-children-collapsed">
            <a
              v-for="item in menuItems.archive"
              :key="item.key"
              :class="['menu-item-collapsed', { active: selectedKeys.includes(item.key) }]"
              @click="handleMenuClick(item.key)"
              :title="item.label"
            >
              {{ item.icon }}
            </a>
          </div>
        </div>
        <div v-if="menuItems.salary.length > 0" class="menu-section">
          <div class="menu-title" :class="{ collapsed }">
            <span class="menu-icon">💰</span>
            <span v-if="!collapsed" class="menu-label">薪酬管理</span>
          </div>
          <div v-if="!collapsed" class="menu-children">
            <a
              v-for="item in menuItems.salary"
              :key="item.key"
              :class="['menu-item', { active: selectedKeys.includes(item.key) }]"
              @click="handleMenuClick(item.key)"
            >
              <span class="menu-item-icon">{{ item.icon }}</span>
              <span class="menu-item-label">{{ item.label }}</span>
            </a>
          </div>
          <div v-else class="menu-children-collapsed">
            <a
              v-for="item in menuItems.salary"
              :key="item.key"
              :class="['menu-item-collapsed', { active: selectedKeys.includes(item.key) }]"
              @click="handleMenuClick(item.key)"
              :title="item.label"
            >
              {{ item.icon }}
            </a>
          </div>
        </div>
        <div v-if="menuItems.role.length > 0" class="menu-section">
          <div class="menu-title" :class="{ collapsed }">
            <span class="menu-icon">👥</span>
            <span v-if="!collapsed" class="menu-label">角色权限</span>
          </div>
          <div v-if="!collapsed" class="menu-children">
            <a
              v-for="item in menuItems.role"
              :key="item.key"
              :class="['menu-item', { active: selectedKeys.includes(item.key) }]"
              @click="handleMenuClick(item.key)"
            >
              <span class="menu-item-icon">{{ item.icon }}</span>
              <span class="menu-item-label">{{ item.label }}</span>
            </a>
          </div>
          <div v-else class="menu-children-collapsed">
            <a
              v-for="item in menuItems.role"
              :key="item.key"
              :class="['menu-item-collapsed', { active: selectedKeys.includes(item.key) }]"
              @click="handleMenuClick(item.key)"
              :title="item.label"
            >
              {{ item.icon }}
            </a>
          </div>
        </div>
      </nav>
    </aside>

    <main class="main-content">
      <div class="content-wrapper">
        <RouterView />
      </div>
    </main>
  </div>
</template>

<style scoped>
.layout-container {
  display: flex;
  height: 100vh;
  background: #f5f5f7;
  font-family:
    -apple-system, BlinkMacSystemFont, 'SF Pro Display', 'SF Pro Text', Helvetica, Arial, sans-serif;
}

.sidebar {
  width: 260px;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(20px) saturate(180%);
  -webkit-backdrop-filter: blur(20px) saturate(180%);
  border-right: 1px solid rgba(0, 0, 0, 0.06);
  display: flex;
  flex-direction: column;
  transition: width 0.3s cubic-bezier(0.25, 0.1, 0.25, 1);
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.04);
}

.sidebar.collapsed {
  width: 80px;
}

.sidebar-header {
  padding: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
}

.logo {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo-text {
  font-size: 18px;
  font-weight: 600;
  color: #1d1d1f;
  letter-spacing: -0.3px;
}

.collapse-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: rgba(0, 0, 0, 0.04);
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #86868b;
  transition: all 0.2s;
}

.collapse-btn:hover {
  background: rgba(0, 0, 0, 0.08);
  color: #1d1d1f;
}

.collapse-btn svg {
  width: 16px;
  height: 16px;
}

.user-info {
  padding: 16px 20px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.user-role {
  font-size: 13px;
  font-weight: 500;
  color: #0071e3;
  background: rgba(0, 113, 227, 0.1);
  padding: 6px 12px;
  border-radius: 8px;
  text-align: center;
}

.logout-btn {
  width: 100%;
  padding: 8px 12px;
  border: none;
  background: rgba(0, 0, 0, 0.04);
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  color: #86868b;
  font-size: 13px;
  font-weight: 500;
  transition: all 0.2s;
}

.logout-btn:hover {
  background: rgba(255, 59, 48, 0.1);
  color: #ff3b30;
}

.logout-btn svg {
  width: 16px;
  height: 16px;
}

.user-info-collapsed {
  padding: 16px 0;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
  display: flex;
  justify-content: center;
}

.logout-btn-collapsed {
  width: 48px;
  height: 48px;
  border: none;
  background: rgba(0, 0, 0, 0.04);
  border-radius: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #86868b;
  transition: all 0.2s;
}

.logout-btn-collapsed:hover {
  background: rgba(255, 59, 48, 0.1);
  color: #ff3b30;
}

.logout-btn-collapsed svg {
  width: 20px;
  height: 20px;
}

.menu {
  flex: 1;
  overflow-y: auto;
  padding: 16px 0;
}

.menu-section {
  margin-bottom: 8px;
}

.menu-title {
  padding: 8px 20px;
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 13px;
  font-weight: 600;
  color: #86868b;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.menu-title.collapsed {
  justify-content: center;
  padding: 8px;
}

.menu-icon {
  font-size: 16px;
}

.menu-label {
  flex: 1;
}

.menu-children {
  padding: 4px 0;
}

.menu-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px 20px 10px 44px;
  color: #1d1d1f;
  text-decoration: none;
  font-size: 14px;
  transition: all 0.2s;
  cursor: pointer;
  border-left: 3px solid transparent;
}

.menu-item:hover {
  background: rgba(0, 113, 227, 0.06);
  color: #0071e3;
}

.menu-item.active {
  background: rgba(0, 113, 227, 0.1);
  color: #0071e3;
  border-left-color: #0071e3;
  font-weight: 500;
}

.menu-item-icon {
  font-size: 16px;
}

.menu-item-label {
  flex: 1;
}

.menu-children-collapsed {
  padding: 4px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.menu-item-collapsed {
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12px;
  font-size: 20px;
  cursor: pointer;
  transition: all 0.2s;
  color: #86868b;
}

.menu-item-collapsed:hover {
  background: rgba(0, 113, 227, 0.1);
  color: #0071e3;
}

.menu-item-collapsed.active {
  background: rgba(0, 113, 227, 0.15);
  color: #0071e3;
}

.main-content {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.content-wrapper {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  background: #f5f5f7;
}
</style>
